package com.vipshop.compass.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileUtil {
	private static Log log = LogFactory.getLog(FileUtil.class);

	public static void deleteAll(File file) {

		if (file.isFile()) {
			file.delete();
		} else {
			File[] files = file.listFiles();
			if (files != null)
				for (int i = 0; i < files.length; i++) {
					deleteAll(files[i]);
					files[i].delete();
				}

			// if (file.exists())
			// file.delete();
		}
	}

	/**
	 * 
	 * @param dir
	 * @return boolean Returns "true" if all deletions were successful. If a
	 *         deletion fails, the method stops attempting to delete and returns
	 *         "false".
	 */
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		return dir.delete();
	}

	/**
	 * @param dir
	 */
	public static void doDeleteEmptyDir(String dir) {
		boolean success = (new File(dir)).delete();
		if (success) {
			System.out.println("Successfully deleted empty directory: " + dir);
		} else {
			System.out.println("Failed to delete empty directory: " + dir);
		}
	}

	public static void main(String args[]) {
		String path = "C:\\TEMP";
		File file = new File(path);
		FileUtil.deleteAll(file);
	}

	public static void writeFile(InputStream input, String path) throws IOException {
		try {

			// write the inputStream to a FileOutputStream
			OutputStream out = new FileOutputStream(new File(path));

			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = input.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}

			input.close();
			out.flush();
			out.close();

			log.info("===>New file created!");
		} catch (IOException e) {
			throw e;
		}
	}

}
